﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WeAppsCenter.Core
{
    public static class DotNetDetector
    {

        public static bool IsDotNetInstalled
        {
            get => DotNetInstalled();
        }
        private static bool DotNetInstalled()
        {
            try
            {
                RunCommandLine("");
            }
            catch (System.ComponentModel.Win32Exception)
            {
                return false;
            }
            return true;
        }

        public static bool DotNetInstalled(string version)
        {
            if (Directory.Exists("C:\\Program Files\\dotnet\\shared\\Microsoft.WindowsDesktop.App"))
            {
                foreach (var item in Directory.GetDirectories("C:\\Program Files\\dotnet\\shared\\Microsoft.WindowsDesktop.App"))
                {
                    string folderName = item.Replace("C:\\Program Files\\dotnet\\shared\\Microsoft.WindowsDesktop.App\\", "");
                    if (folderName.StartsWith(version.Substring(0,version.Length-1)))
                    {
                        return true;
                    }
                }
                return false;
            }
            else
            {
                return false;
            }
        }

        public static string RunCommandLine(string arg)
        {
            Process process = new Process();
            process.StartInfo.FileName = "dotnet";
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.Arguments = arg;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            StreamReader streamReader = process.StandardOutput;
            string output = streamReader.ReadLine();
            while (!streamReader.EndOfStream)
            {
                output += streamReader.ReadLine();
            }
            return output;
        }

        public static string GetDotNetDownloadLink(string version)
        {
            string dotNetVersionUrl = $"https://dotnetcli.azureedge.net/dotnet/WindowsDesktop/{version}/latest.version";
            string latestVersion;
            using (HttpClient getDotNetVersionClient = new HttpClient())
            {
               latestVersion = getDotNetVersionClient.GetStringAsync(dotNetVersionUrl).Result;

            }
            return $"https://dotnetcli.azureedge.net/dotnet/WindowsDesktop/{latestVersion}/windowsdesktop-runtime-{latestVersion}-win-x64.exe";
        }
    }
}
